package com.shelpe.services.sustainer.controller;

import java.util.Date;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.shelpe.services.sustainer.entity.jpa.SustainerQueue;
import com.shelpe.services.sustainer.repository.jpa.SustainerQueueRepository;

import lombok.Data;

@Controller
@RequestMapping("/sustainerservice")
public class SustainerController {
	@Autowired
	private SustainerQueueRepository sustainerQueueRepository;
	
	@RequestMapping(path="/sustainers", method=RequestMethod.POST)
	@ResponseBody
	public SustainerDto createSustainer(@RequestBody SustainerDto dto){
		SustainerQueue queue = new SustainerQueue();
		BeanUtils.copyProperties(dto, queue);
		queue.setSequence(0);
		queue.setCreatedTime(new Date());
		queue.setModifiedTime(new Date());
		this.sustainerQueueRepository.save(queue);
		return dto;
	}
	
	@RequestMapping(path="/sustainers", method=RequestMethod.DELETE)
	@ResponseBody
	public SustainerDto createSustainer(@RequestParam("callee_id") long calleeID, @RequestParam("callee_type") String calleeType){
		SustainerQueue queue = this.sustainerQueueRepository.findOne(new SustainerQueue.SustainerQueuePK(calleeID + "", calleeType));
		Assert.notNull(queue, "sustainer_not_found");
		this.sustainerQueueRepository.delete(queue);
		
		SustainerDto dto = new SustainerDto();
		BeanUtils.copyProperties(queue, dto);
		return dto;
	}
	
	@Data
	public static class SustainerDto{
		@JsonProperty("callee_type")
		private String calleeType;
		@JsonProperty("callee_id")
		private String calleeID;
		
		@JsonProperty("service_id")
		private String serviceID;
		private String path;
		private String parameter;
		
		@JsonProperty("next_jump_point")
		@JsonFormat(shape=Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
		private Date nextJumpPoint;
	}
	
}
